package com.atguigu.ssyx.acl.service.impl;

import com.atguigu.ssyx.acl.mapper.PermissionMapper;
import com.atguigu.ssyx.acl.service.PermissionService;
import com.atguigu.ssyx.acl.service.RolePermissionService;
import com.atguigu.ssyx.acl.utils.PermissionHelper;
import com.atguigu.ssyx.model.acl.AdminRole;
import com.atguigu.ssyx.model.acl.Permission;
import com.atguigu.ssyx.model.acl.Role;
import com.atguigu.ssyx.model.acl.RolePermission;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 权限服务实现类
 * </p>
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission>
        implements PermissionService {

	@Autowired
	private PermissionService permissionService;
	@Autowired
	private RolePermissionService rolePermissionService;

	//获取所有菜单
    @Override
    public List<Permission> queryAllMenu() {
        //获取全部权限数据
        List<Permission> allPermissionList = baseMapper.selectList(
                new QueryWrapper<Permission>().orderByAsc("CAST(id AS SIGNED)"));

        //把权限数据构建成树形结构数据
        List<Permission> result = PermissionHelper.bulid(allPermissionList);
        return result;
    }

    //递归删除菜单
    @Override
    public boolean removeChildById(Long id) {
        //1  创建list集合idList，封装所有要删除的菜单id
        List<Long> idList = new ArrayList<>();
        this.selectChildListById(id, idList);
        idList.add(id);
        //调用方法根据多个菜单id删除
        baseMapper.deleteBatchIds(idList);
        return true;
    }

    /**
     * 递归获取子节点
     *
     * @param id
     * @param idList
     */
    private void selectChildListById(Long id, List<Long> idList) {
        List<Permission> childList = baseMapper.selectList(
                new QueryWrapper<Permission>().eq("pid", id).select("id"));
        childList.stream().forEach(item -> {
            idList.add(item.getId());
            this.selectChildListById(item.getId(), idList);
        });
    }


	//根据角色id获取菜单权限数据
    @Override
    public Map<String, Object> findPermissionByRoleId(Long roleId) {
		//1、查询所有的菜单权限
		List<Permission> allPermissionList = baseMapper.selectList(null);

		//2、根据拥有的菜单权限id，获取角色已分配的菜单权限id列表
		//2.1 根据角色查询  角色权限关系表  role_permission  查询角色分配权限id列表
		LambdaQueryWrapper<RolePermission> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(RolePermission::getRoleId, roleId);
		List<RolePermission> rolePermissionList = rolePermissionService.list(wrapper);
		//2.2 通过第一步返回返回集合，获取所有权限id的列表List<Long>
		List<Long> permissionIdList = new  ArrayList<>();
		for (RolePermission rolePermission : rolePermissionList) {
			Long permissionId = rolePermission.getRoleId();
			permissionIdList.add(permissionId);
		}
		//2.3 创建新的list集合，用于封装已分配权限
		List<Permission> assignPermissions = new ArrayList<Permission>();
		//2.4 遍历所有角色列表allRolesList，得到每个角色id
		//判断当前角色id，是否包含在已分配角色id列表中，封装到2.3里面新的list集合
		for (Permission permission : allPermissionList) {
			//已分配
			if (permissionIdList.contains(permission.getId())) {
				assignPermissions.add(permission);
			}
		}
		//创建返回的Map，封装到map集合中
		Map<String, Object> roleMap = new HashMap<>();
		roleMap.put("allRolesList", allPermissionList);//所有权限
		roleMap.put("assignRoles", assignPermissions);//用户分配权限id集合
		return roleMap;
    }

	@Override
	public void saveRolePermissionRealtionShip(Long roleId, Long[] permissionIds) {
		//删除角色分配的权限数据
		QueryWrapper<RolePermission> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("role_id", roleId);
		rolePermissionService.remove(queryWrapper);

		//分配新的权限
		//遍历所有权限id，得到每个权限id，拿着每个权限id+角色id添加到rolePermission角色权限表中
		List<RolePermission> rolePermissionList = new ArrayList<>();
		for ( Long permissionId : permissionIds) {
			if (StringUtils.isEmpty(permissionId)) continue;
			RolePermission rolePermission = new RolePermission();
			rolePermission.setRoleId(roleId);
			rolePermission.setPermissionId(permissionId);
			rolePermissionList.add(rolePermission);
		}
		rolePermissionService.saveBatch(rolePermissionList);
	}

}